from django.shortcuts import render
from .models import Project
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from django.http import JsonResponse
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
# Create your views here.


@api_view('POST')
def add(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    status=data.get('status')
    Project(name=name,status=status)
    return JsonResponse({
        'code':200,
        'msg':'添加成功'
    })

@api_view(['GET'])
def chaxun(request):
    datas=JSONParser().parse(request)
    lis=[]
    for data in datas:
        lis.append({
            '项目名':data.name,
            '项目状态':data.status,
        })
    return JsonResponse({
        'code':200,
        "msg":'查询成功',
        'data':lis
    })

@api_view('DELETE')
def delete(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    d=Project.objects.filter(name=name).first()
    d.delete()
    return JsonResponse({
        'code':200,
        'msg':'删除成功'
    })

@api_view('PUT')
def update(request):
    data=JSONParser().parse(request)
    name=data.get('name')
    # name=data.get('name')
    d=Project.objects.filter(name=name)
    if d.exists() is False:
        return JsonResponse({
            'code':200,
            'msg':'项目不存在'
        })
    d=Project.objects.get(name=name)
    d.save()
    return JsonResponse({
        'code':200,
        'msg':'修改成功'
    })

@api_view(['GET'])
def fenye(request):
    page=request.GET.get('page')
    pagesize=request.GET.get('pagesize')
    datas= Project.objects.filter().values()
    pageobj=Paginator(datas.pagesize)
    try:
        danye=pageobj.page(page)
    except EmptyPage:
        danye=pageobj.page(1)
    lis=[]
    for item in pageobj.objects.list:
        lis.append({
            '项目名':item.get('name'),
            '项目状态':item.get('status')
        })
    return JsonResponse({
        'code':200,
        'msg':'修改成功',
        'data':lis
    })



